package de.tudresden.st.cbse.calendar;

import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import de.tudresden.st.cbse.calendar.appointment.Appointment;
import de.tudresden.st.cbse.calendar.user.User;

@Stateless
@Remote(RemoteCalendarManager.class)
public class CalendarManagerBean implements RemoteCalendarManager {

    @PersistenceContext
    EntityManager em;

    @Override
    public Calendar getCalendarForUser(String email) {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<User> q = cb.createQuery(User.class);
        Root<User> r = q.from(User.class);

        Predicate pEntry = cb.equal(r.get("email"), email);

        q.where(pEntry);

        TypedQuery<User> tq = em.createQuery(q);

        for (User user : tq.getResultList()) {
            if (email.equals(user.getEmail())) {
                return user.getCalendar();
            }
        }

        return null;
    }
    
    @Override
    public void addAppointment(Calendar calendar, Appointment appointment) {
        em.persist(appointment);
        calendar.add(appointment);
        em.merge(calendar);
    }
}
